﻿using IGG.POCO;
using IGGCore;
using IGGCore.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace IGG.Formatters
{
    public class TeamSectionManager
    {
        private Random rnd = new Random();
        private Tweet[] tweets;
        private Team activeTeam;
        private int pitcherIdx = 0;
        private List<Prospect> prospects = new List<Prospect>();

        public bool Ready { get; set; }

        public void LoadTeamSection()
        {
            Ready = false;
            activeTeam = new Team();
            string[] teams = { "LAA", "ATL", "ARI", "BAL", "BOS", "CHC", "CHW", "CIN", "CLE", "COL", "DET", "HOU", "KC", "LAD", "MIA", "MIL", "MIN", "NYM", "NYY", "OAK", 
                               "PHI", "PIT", "SD", "SF", "SEA", "STL", "TB", "TEX", "TOR", "WAS"};

            activeTeam.Code = teams[rnd.Next(teams.Length)];
            TeamCruncher.CrunchTeam(activeTeam);

            NewsParser newsParser = new NewsParser();
            activeTeam.News = newsParser.GetRssNews(activeTeam.RssFeed, 9, false);

            DepthChartParser depthParser = new DepthChartParser();
            activeTeam.DepthChart = depthParser.GetDepthChart(activeTeam.DepthChartSource);

            // LOAD PROSPECTS
            prospects.Clear();
            string m_filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + CoreConstants.FILE_PATH_PROSPECTS;
            StreamReader reader = new StreamReader(m_filePath);
            string line = reader.ReadLine();
            while (line != null)
            {
                Prospect prospect = new Prospect();
                string[] props = line.Split(new char[]{'|'});
                prospect.Name = props[2];
                prospect.Rank = int.Parse(props[1]);
                prospect.Team = props[0];
                prospect.Pos = props[3];
                prospects.Add(prospect);

                line = reader.ReadLine();
            }
            reader.Close();

            // TWITTER
            TwitterParser twitterParser = new TwitterParser();
            tweets = twitterParser.GetBeatTweets(activeTeam.BeatWriters, 5);

            Ready = true;
        }

        public void PublishTeamSection()
        {
            
            Output.Write(" AND NOW SOME NEWS FROM ONE OF YOUR FAVORITE TEAMS, ");
            Output.WriteLine("THE " + activeTeam.City.ToUpper() + " " + activeTeam.Name.ToUpper() + "....");
            Output.WriteLine();

            // CUSTOM TEAM CONTENT
            string line = null;
            Random rnd = new Random();

            // STREAK
            int strkCount = int.Parse(activeTeam.Streak.Substring(2));
            string littleStreak = null;
            if (activeTeam.Streak.Contains("W"))
            {
                if (strkCount > 10)
                {
                    line = "Incredible! They have won " + strkCount + " in a row!";
                }
                else if (strkCount > 6)
                {
                    line = "They're on a roll... " + strkCount + " wins in a row!";
                }
                else if (strkCount > 3)
                {
                    line = "They are on a " + strkCount + " wins streak!";
                }
                else if (strkCount > 1)
                {
                    littleStreak = ". They have won their last " + strkCount + " games";
                }
            }
            else
            {
                if (strkCount > 10)
                {
                    line = "Good grief! They have lost " + strkCount + " in a row!";
                }
                else if (strkCount > 6)
                {
                    line = "They're on a miserable streak... " + strkCount + " losses in a row!";
                }
                else if (strkCount > 3)
                {
                    line = "They are on a " + strkCount + " games losing streak...";
                }
                else if (strkCount > 1)
                {
                    littleStreak = ". They have lost their last " + strkCount + " games";
                }
            }

            // LAST 10
            string[] rates = activeTeam.LastTen.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
            int wins = int.Parse(rates[0]);
            int losses = int.Parse(rates[1]);
            if (line == null)
            {

                if (wins == 9)
                {
                    line = "They are red hot! They have won nine of their last ten games!";
                }
                else if (wins == 8)
                {
                    line = "They are in fire! They have won eight of their last ten games!";
                }
                else if (wins == 7)
                {
                    line = "Seven wins and only three losses in their last ten games";
                }
                else if (losses == 9)
                {
                    line = "They stink. They have only won one game in their last ten...";
                }
                else if (losses == 8)
                {
                    line = "They are cold as ice. Eight losses in their last ten games...";
                }
                else if (losses == 7)
                {
                    line = activeTeam.Wins + " wins and " + activeTeam.Losses + " losses. Seven losses and only three wins in their last ten games...";
                }
            }

            // PCT
            //if (activeTeam.Wins + activeTeam.Losses > 30)
            //{
            //    float pct = 0F;
            //    if (activeTeam.Percent == "")
            //    {

            //    }
            //}

            // HOME

            // ROAD

            // SCORED

            // ALLOWED

            // DIFF


            if (line == null)
            {
                if (activeTeam.Losses == activeTeam.Wins)
                {
                    line = "They are playing for .500 (" + activeTeam.Wins + " wins and " + activeTeam.Losses + " losses)";
                }
                else if (activeTeam.Losses > activeTeam.Wins)
                {
                    if ((activeTeam.Losses + activeTeam.Wins) < 20)
                    {
                        line = "They have a bad start (" + activeTeam.Wins + " wins and " + activeTeam.Losses + " losses)";
                    }
                    else
                    {
                        line = "They're having a difficult season (" + activeTeam.Wins + " wins and " + activeTeam.Losses + " losses)";
                    }
                }
                else
                {
                    if ((activeTeam.Losses + activeTeam.Wins) < 20)
                    {
                        line = "They have a good start (" + activeTeam.Wins + " wins and " + activeTeam.Losses + " losses)";
                    }
                    else
                    {
                        line = "They're having a good season (" + activeTeam.Wins + " wins and " + activeTeam.Losses + " losses)";
                    }
                }
                if (littleStreak != null)
                {
                    line += littleStreak;
                }

                // GAMES BEHIND
                if (activeTeam.GamesBack == "½" && (activeTeam.Losses + activeTeam.Wins) > 30)
                {
                    line += ". They're only half a game behind in their division!";
                }
                else if (activeTeam.GamesBack == "1" && (activeTeam.Losses + activeTeam.Wins) > 30)
                {
                    line += ". They're only one game behind in their division!";
                }
                else if (activeTeam.GamesBack == "1½" && (activeTeam.Losses + activeTeam.Wins) > 30)
                {
                    line += ". They are one and a half games behind in their division.";
                }
                else if (activeTeam.GamesBack == "2" && (activeTeam.Losses + activeTeam.Wins) > 30)
                {
                    line += ". They are two games from the lead in their division.";
                }
                else if (activeTeam.GamesBack == "-")
                {
                    line += " and they lead their division!";
                }
                Output.WriteLine(" " + line);
            }
            else
            {
                Output.WriteLine(" " + line);
            }

            if (TeamCruncher.teamLeaders.ContainsKey(activeTeam.AltCode))
            {
                Output.WriteLine("");
                Output.WriteLine(" NOTABLE LEADERS...");
                foreach(string lineAs in TeamCruncher.teamLeaders[activeTeam.AltCode])
                {
                    Output.WriteLine(" " + lineAs);
                }
            }
            

            // CUSTOM TEAM CONTENT

            Output.WriteLine();
            if (activeTeam.News != null && activeTeam.News.Count > 2)
            {
                int i = 0;
                int idex = 0;
                while (i<4)
                {
                    if (activeTeam.News[idex].HeadlineRatio > -100)
                    {
                        Output.WriteLine(" " + activeTeam.News[idex].Title.ToUpper());
                        Output.FormatLongText(activeTeam.News[idex].Content);
                        Output.WriteLine();
                        i++;
                    }
                    idex++;
                }
            }
            FormatDepthChart(activeTeam.DepthChart);

            Output.WriteLine(" Current Prospects:");

            foreach (Prospect pro in prospects)
            {
                if (pro.Team.ToUpper().Trim() == activeTeam.Code.ToUpper().Trim())
                {
                    Output.WriteLine(" " + pro.Rank + " - " + pro.Name + " (" + pro.Pos + ")");
                }

            }

            Output.WriteLine();

            if (tweets != null && tweets.Length > 0)
            {
                for (int i = 0; i < 4; i++)
                {
                    Output.WriteLine(" " + tweets[i].Author.ToUpper());
                    Output.FormatLongText(tweets[i].Text);
                    Output.WriteLine();

                }
            }
        }

        private void AddToBench(Player[] players, Dictionary<string, string> bench, string label)
        {
            for (int i = 0; i < players.Length; i++)
            {
                string pos = label;
                if (i == 0)
                {
                    pos = "XX";
                }

                if (bench.ContainsKey(players[i].FirstName.Substring(0, 1) + "." + " " + players[i].LastName))
                {
                    bench[players[i].FirstName.Substring(0, 1) + "." + " " + players[i].LastName] = bench[players[i].FirstName.Substring(0, 1) + "." + " " + players[i].LastName] + ", " + pos;
                }
                else
                {
                    bench.Add(players[i].FirstName.Substring(0, 1) + "." + " " + players[i].LastName, pos);
                }
                
            }
        }

        private Dictionary<string, string> GetBench(DepthChart chart)
        {
            Dictionary<string, string> bench = new Dictionary<string, string>();
            AddToBench(chart.Catchers, bench, "C");
            AddToBench(chart.FirstBases, bench, "1B");
            AddToBench(chart.SecondBases, bench, "2B");
            AddToBench(chart.ThirdBases, bench, "3B");
            AddToBench(chart.Shortstops, bench, "SS");
            AddToBench(chart.LeftFields, bench, "LF");
            AddToBench(chart.CenterFields, bench, "CF");
            AddToBench(chart.RightFields, bench, "RF");
            if (chart.DesignatedHitters!=null)
            {
                AddToBench(chart.DesignatedHitters, bench, "DH");
            }


            Dictionary<string, string> filteredbench = new Dictionary<string, string>();
            foreach(string key in bench.Keys)
            {
                if (bench[key].Contains("XX") == false)
                {
                    filteredbench.Add(key, bench[key]);
                }
            }

            return filteredbench;
        }


        private void FormatDepthChart(DepthChart chart)
        {
            pitcherIdx = 0;
            Dictionary<string, string> bench = GetBench(chart);
            string[] keys = bench.Keys.ToArray();

            bool ended = false;
            while(ended == false)
            {
                string[] cases = new string[4];
                bool found = true;
                switch(pitcherIdx)
                {
                    case 0:
                        cases[0] = ToolBox.GetFormattedStringPadRight("C", 3) + ": " + chart.Catchers[0].FullName;
                        break;
                    case 1:
                        cases[0] = ToolBox.GetFormattedStringPadRight("1B", 3) + ": " + chart.FirstBases[0].FullName;
                        break;
                    case 2:
                        cases[0] = ToolBox.GetFormattedStringPadRight("2B", 3) + ": " + chart.SecondBases[0].FullName;
                        break;
                    case 3:
                        cases[0] = ToolBox.GetFormattedStringPadRight("3B", 3) + ": " + chart.ThirdBases[0].FullName;
                        break;
                    case 4:
                        cases[0] = ToolBox.GetFormattedStringPadRight("SS", 3) + ": " + chart.Shortstops[0].FullName;
                        break;
                    case 5:
                        cases[0] = ToolBox.GetFormattedStringPadRight("LF", 3) + ": " + chart.LeftFields[0].FullName;
                        break;
                    case 6:
                        cases[0] = ToolBox.GetFormattedStringPadRight("CF", 3) + ": " + chart.CenterFields[0].FullName;
                        break;
                    case 7:
                        cases[0] = ToolBox.GetFormattedStringPadRight("RF", 3) + ": " + chart.RightFields[0].FullName;
                        break;
                    case 8:
                        if (chart.DesignatedHitters!=null && chart.DesignatedHitters.Length > 0)
                        {
                            cases[0] = ToolBox.GetFormattedStringPadRight("DH", 3) + ": " + chart.DesignatedHitters[0].FullName;
                        }
                        else
                        {
                            found = false;
                            cases[0] = "";
                        }
                        break;
                    default:
                        found = false;
                        cases[0] = "";
                        break;
                }

                if (pitcherIdx < chart.Pitchers.Length)
                {
                    cases[1] = ToolBox.GetFormattedStringPadRight("SP", 3) + ": " + chart.Pitchers[pitcherIdx].FullName;
                    found = true;
                }
                else
                {
                    cases[1] = "";
                }

                if (pitcherIdx == 0)
                {
                    cases[2] = ToolBox.GetFormattedStringPadRight("CL", 3) + ": " + chart.Relievers[pitcherIdx].FullName;
                    found = true;
                }
                else if (pitcherIdx < chart.Relievers.Length)
                {
                    cases[2] = ToolBox.GetFormattedStringPadRight("RP", 3) + ": " + chart.Relievers[pitcherIdx].FullName;
                    found = true;
                }
                else
                {
                    cases[2] = "";
                }

                if (pitcherIdx == 0)
                {
                    cases[3] = "POSITION PLAYERS BENCH";
                    found = true;
                }
                else if (pitcherIdx-1 < keys.Length)
                {
                    cases[3] = ToolBox.GetFormattedStringPadRight(keys[pitcherIdx-1], 18) + bench[keys[pitcherIdx-1]];
                    found = true;
                }
                else
                {
                    cases[3] = "";
                }


                Output.WriteLine(" " + ToolBox.GetFormattedStringPadRight(cases[0], 30)
                    + ToolBox.GetFormattedStringPadRight(cases[1], 30) + ToolBox.GetFormattedStringPadRight(cases[2], 30) + ToolBox.GetFormattedStringPadRight(cases[3], 30));

                ended = !found;
                pitcherIdx++;
            }

            if (chart.DLs!=null && chart.DLs.Length>0)
            {
                Output.WriteLine(" DL:");
                foreach(Player l in chart.DLs)
                {
                    Output.Write(" " + l.FullName);
                    if (l.Report.Contains("60"))
                    {
                        Output.Write(" - 60-Day DL");
                    }

                    foreach(Player dd in chart.Notes)
                    {
                        if (l.FullName == dd.FullName)
                        {
                            Output.Write(" (" + dd.Report + ")");
                        }
                    }
                    Output.WriteLine();
                }
                Output.WriteLine();
            }
        }
        
    }
}
